<!--建立考核模板第二步--- 添加指标 -->
<template>
  <div class="app-container">
    <div style="height: 700px;" v-if="page2">
      <!-- 添加指标按钮 -->
      <el-row>
        <el-button
          @click="addEquipment()"
          style="
          background-color: #3B95FF;
           color: #fff;
       border-radius:4px
        height: 32px;
      line-height: 6px;
      margin-bottom: 10px;
         "
        >添加指标</el-button>
        <el-button
          @click="deleteSelected()"
          style="
           background-color: #E86565;
           color: #fff;
       border-radius:4px
        height: 32px;
      line-height: 6px;
      margin-bottom: 10px;
      "
          :disabled="deletes"
        >批量删除</el-button>
      </el-row>
      <!-- 表格信息 -->
      <el-row>
        <el-table
          :data="
          tableData"
          style="width: 100%; color: #333333; font-size: 14px"
          height="500"
          align="center"
          :header-cell-style="{ background: '#ECF1F9',  }"
          @selection-change="handleSelectionChangeDepartment"
        >
          <el-table-column type="selection" width="80" align="center"></el-table-column>
          <el-table-column fixed type="index" align="center" label="编号" width="80"></el-table-column>
          <el-table-column prop="name" align="center" label="指标名称"></el-table-column>
          <el-table-column prop="num" align="center" label="填写数量" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.num == -1">不限制</span>
              <span v-else>{{ scope.row.num }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="createBy" align="center" label="创建人" width="120"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>

          <el-table-column prop="latitudeBeans" align="center" label="维度">
            <template slot-scope="scope">
              <div
                style="text-align:center"
                v-for="(item,index) in scope.row.latitudeBeans"
                :key="index"
              >
                <span>{{ "维度"+ (index+1) + ":" + item.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.row)"
                type="text"
                size="small"
                style="color: red"
              >删除</el-button>
              <el-button @click.native.prevent="editRow(scope.row)" type="text" size="small">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-pagination
            style="text-align: right;margin-top:16px"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10]"
            :page-size="pageSize"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-row>
      <!-- 下一页按钮 -->
      <el-row style="margin-left: 43%;">
        <el-button
          @click="upPage()"
          round
          style="width:113px;height:43px;font-size:18px;border-radius: 50px;"
        >上一步</el-button>
        <el-button
          @click.prevent="nextPage"
          type="primary"
          class="nextOne"
          round
          style="width:113px;height:43px;font-size:18px;border-radius: 50px;"
        >下一步</el-button>
      </el-row>
      <!-- 添加指标弹出框 -编辑弹出框-->
      <el-dialog
        :append-to-body="true"
        :title="titleMap[dialogStatus]"
        :visible.sync="addTarget"
        width="29%"
      >
        <el-form
          label-position="left"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          style="margin-left: 35px"
        >
          <el-form-item label="指标名称" :label-width="formLabelWidth" prop="name">
            <el-input autocomplete="off" v-model="ruleForm.name" style="width: 330px"></el-input>
          </el-form-item>
          <el-form-item label="填写数量" :label-width="formLabelWidth" prop="type">
            <el-radio-group v-model="ruleForm.type" @change="changeRadio" fill="#cccccc">
              <el-radio label="1">不限制</el-radio>
              <el-radio label="2">限制</el-radio>
            </el-radio-group>
            <el-input
              autocomplete="off"
              v-model="ruleForm.num"
              style="width: 70px; margin-left: 15px"
              :disabled="no_input"
            ></el-input>
          </el-form-item>
          <!-- :prop="`latitudeBeans[${index}].name`" -->
          <!-- :rules="rules.dynamicItem.name" -->
          <el-form-item
            :label="'维度' + (index + 1)"
            :label-width="formLabelWidth"
            :prop="`dynamicItem[${index}].name`"
            v-for="(item, index) in ruleForm.dynamicItem"
            :key="index + 1"
       
            style="position: relative"
          >
            <el-input autocomplete="off" v-model="item.name" style="width: 330px"></el-input>
            <el-button
              @click.native.prevent="deleteItem(index, item)"
              v-if="allBtn"
              type="text"
              style="
             color: red;
              font-size: 22px;
             position: absolute;
             bottom: -2px;
             right: 44px;
              "
              icon="el-icon-remove-outline"
            ></el-button>
          </el-form-item>
          <el-button
            @click="add_dimension"
            v-if="allBtn"
            class="add_dimension"
            style="
             border: none;
             background-color: rgba(76, 106, 248, 0);
            margin-left: -23px;
            "
          >+ 添加维度</el-button>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="closeTargets('ruleForm')"
            style="
             background-color: rgba(213, 215, 220);
            height: 30px;
          line-height: 5px;
            "
          >取 消</el-button>
          <el-button
            type="primary"
            @click="addTargets('ruleForm')"
            style="
         background-color: rgb(76 106 248);
        height: 30px;
           line-height: 5px;
            "
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <threeStep v-if="page3" :personInfo1="personInfo" @giveFather="updateTitle"></threeStep>
  </div>
</template>
  
  <script>
import threeStep from "./threeStep.vue";
import {
  addTowStep,
  getZhiBiaoList,
  deleteTowStep,
  editTowStep,
  deleteAllzhibiao
} from "@/api2/kaohe";
export default {
  components: {
    threeStep: threeStep
  },
  props: {
    personInfo: {
      type: String
    }
  },
  data() {
    return {
      ids1: this.idd,
      deletes: true,
      multipleSelectionDepartment: [], // 用于保存选中的行
      page2: true,
      page3: false,
      number: 1,
      ids: "",
      allBtn: true, //添加维度,删除维度按钮的开关
      addTarget: false, //添加指标弹窗开关
      formLabelWidth: "80px", //label-width
      no_input: true, //限制选项input框禁用字符
      deleteStyle: true, //删除维度按钮显示隐藏
      // 分页属性定义如下{
      pageNum: 1, //当前页
      total: 0, //总条数
      pageSize: 10, //当前页容量
      // }
      //表格数据数组
      tableData: [],
      assessTemplateId: "",
      tableColumns: { list: [], header: [] }, //维度数组
      //弹层数组
      ruleForm: {
        type: "",
        name: "", //指标名称
        num: "", //填写数量
        //维度
        dynamicItem: [
          {
            key: "1",
            name: ""
          }
        ]
      },
      //规则校验
      rules: {
        //指标名称校验
        name: [
          { required: true, message: "请输入指标名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30个字符", trigger: "blur" }
        ],
        //填写数量校验
        type: [
          { required: true, message: "请选择填写数量", trigger: "change" }
        ],
        //维度校验
        dynamicItem: {
          name: [
            { required: true, message: "请输入维度", trigger: "blur" },
            {
              min: 1,
              max: 30,
              message: "长度在 1 到 30 个字符",
              trigger: "blur"
            }
          ]
        }
      },

      //新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: { addEquipment: "添加指标", editEquipment: "编辑指标" },
      //新增和编辑弹框标题
      dialogStatus: ""
    };
  },
  created() {
    this.getzhibiaoLists(); //获取指标表格数据
  },
  watch: {
    "tableColumns.list"(newVal) {
      const headerSet = new Set();
      newVal?.forEach(column =>
        Object.keys(column).map(item => item !== "file" && headerSet.add(item))
      );
      this.tableColumns.headers = [...headerSet];
      // console.log(this.tableColumns.headers);
    }
  },

  methods: {
    //上一步
    upPage() {
      console.log(this.personInfo);
      this.$emit("giveFathers", this.personInfo);
      this.page1 = false;
      this.page2 = true;
    },
    updateTitle(e) {
      //声明这个函数
      if (e == false) {
        this.page2 = true;
        this.page3 = false;
      }
    },
    handleSelectionChangeDepartment(val) {
      this.multipleSelectionDepartment = val;
      if (val) {
        this.deletes = false;
      } else {
        this.deletes = true;
      }
    },
    // 批量删除
    deleteSelected() {
      this.$confirm("此操作将删除选中所有内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let arr = [];
          let vals = this.multipleSelectionDepartment; //选中的值
          if (vals) {
            vals.map(item => {
              arr.push(item.id);
            });
          }
          const ids = { ids: arr.join() };
          deleteAllzhibiao(ids).then(res => {
            if (res.code == 0) {
              this.$message.success("删除成功");
              this.getzhibiaoLists();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    nextPage() {
      this.$emit("giveFather", "3");
      this.page2 = false;
      this.page3 = true;
    },
    // 添加指标按钮
    addEquipment() {
      this.addTarget = true;
      this.allBtn = true;
      this.no_input = true;
      //新增弹框标题
      this.dialogStatus = "addEquipment";
      this.ruleForm = {
        assessTemplateId: "",
        num: "",
        name: "", //指标名称
        type: "1", //填写数量
        //维度
        dynamicItem: [
          {
            key: "1",
            name: "",
            fillingStatus: "1",
            content: [
              {
                num: "",
                specificContent: ""
              }
            ]
          }
        ]
      };
    },
    // 表格内编辑按钮的点击事件
    editRow(rows) {
      console.log(rows);
      if (rows.num !== -1) {
        this.no_input = false;
      } else {
        this.no_input = true;
      }
      this.addTarget = true;
      this.allBtn = false;
      this.dialogStatus = "editEquipment";
      this.ids = rows.id;
      this.ruleForm.name = rows.name;
      this.ruleForm.num = rows.num == -1 ? "" : rows.num;
      this.ruleForm.type = rows.num == -1 ? "1" : "2";
      this.ruleForm.dynamicItem = rows.latitudeBeans;
      this.ruleForm.assessTemplateId = rows.assessTemplateId;
    },
    // 表格内删除按钮的点击事件
    deleteRow(rows) {
      const id = rows.id;
      this.$confirm("此操作将删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res1 => {
          deleteTowStep(id).then(res => {
            if (res.data === true) {
              this.$message.success("删除成功");
              const totalPage = Math.ceil((this.total - 1) / this.pageSize);
              // 记住删除最后一条数据时当前码是最后一页
              const pageNums =
                this.pageNum > totalPage ? totalPage : this.pageNum;
              // 重新记录当前页码
              this.pageNum = pageNums < 1 ? 1 : pageNums;
              //删除成功 回调列表接口
              this.getzhibiaoLists();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 填写数量 radio单选事件changeRadio
    changeRadio(val) {
      if (val == 2) {
        this.no_input = false;
      } else {
        this.no_input = true;
      }
    },
    // 点击添加维度按钮
    add_dimension() {
      this.ruleForm.dynamicItem.push({
        key: (this.ruleForm.dynamicItem.length + 1).toString(),
        name: "",
        fillingStatus: "1",
        content: [
          {
            num: "",
            specificContent: ""
          }
        ]
      });
    },
    // 删除维度按钮
    deleteItem(index, rows) {
      console.log(index);
      if (index == 0) {
        this.$message.error("至少要添加一个考核维度!");
        return;
      } else {
        this.ruleForm.dynamicItem.splice(index, 1);
      }
    },
    //确定指标按钮点击事件{
    addTargets(formName) {
      if (this.dialogStatus === "addEquipment") {
        const params = {
          assessTemplateId: this.personInfo,
          name: this.ruleForm.name,
          type: this.ruleForm.type,
          latitudeBeans: this.ruleForm.dynamicItem,
          num: this.ruleForm.type == 1 ? "-1" : this.ruleForm.num
        };
        console.log(params);
        this.$refs[formName].validate(async valid => {
          if (valid) {
            const res = await addTowStep(params);
            this.$message({
              message: "指标添加成功",
              type: "success"
            });
            this.getzhibiaoLists();
            this.ruleForm = {
              assessTemplateId: "",
              num: "",
              name: "", //指标名称
              type: "", //填写数量
              //维度
              dynamicItem: [
                {
                  key: "1",
                  name: ""
                }
              ]
            };
            this.addTarget = false;
            this.no_input = true;
            this.$refs[formName].resetFields();
          } else {
            this.$message.error("信息填写不完整!");
            return false;
          }
        });
      } else {
        const params1 = {
          id: this.ids,
          assessTemplateId: this.ruleForm.assessTemplateId,
          name: this.ruleForm.name,
          type: this.ruleForm.type,
          latitudeBeans: this.ruleForm.dynamicItem,
          num: this.ruleForm.num
        };
        console.log(params1);
        this.$refs[formName].validate(async valid => {
          if (valid) {
            const res = await editTowStep(params1);
            console.log(res);
            this.$message({
              message: "指标编辑成功",
              type: "success"
            });
            this.getzhibiaoLists();
            this.ruleForm = {
              assessTemplateId: "",
              type: "",
              name: "", //指标名称
              num: "", //填写数量
              //维度
              dynamicItem: [
                {
                  key: "1",
                  name: ""
                }
              ]
            };
            this.addTarget = false;
            this.no_input = true;
          } else {
            this.$message.error("信息填写不完整!");
            return false;
          }
        });
      }
    },
    //确定指标按钮点击事件}
    //取消指标按钮点击事件{
    closeTargets(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = {
        assessTemplateId: "",
        type: "",
        name: "", //指标名称
        num: "", //填写数量
        //维度
        dynamicItem: [
          {
            key: "1",
            name: ""
          }
        ]
      };
      this.addTarget = false;
      this.no_input = true;
      this.$message({
        message: "已取消"
      });
    },
    //取消指标按钮点击事件}
    //分页逻辑{
    //切换每页条数容量
    handleSizeChange(val) {
      this.pageSize = val;
      this.getzhibiaoLists(this.pageNum, this.pageSize);
    },
    //切换当前页
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getzhibiaoLists();
    },
    //获取表格数据
    getzhibiaoLists() {
      console.log(this.personInfo);
      const params = {
        assessTemplateId: this.personInfo,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      let arr = [];
      getZhiBiaoList(params)
        .then(res1 => {
          this.total = res1.total; //总条数
          res1.data.sort(
            (a, b) =>
              new Date(b.createTime).getTime() -
              new Date(a.createTime).getTime()
          ); //这是升序，倒序的话翻过来
          this.tableData = res1.data;
          console.log(res1.data);
          res1.data.forEach(element => {
            arr.push(element.latitudeBeans);
          });
          this.latitudeBeansd = arr;
        })
        .catch(e => {
          console.log(e);
        });
    }
    //分页逻辑}
  }
};
</script>
  
  <style lang="scss" scoped>
/* 共同样式 */
.add_dimension {
  color: blue;
}
.delete_dimension {
  color: red;
}
.add_dimension:hover {
  color: rgb(72, 72, 234);
}
.delete_dimension:hover {
  color: rgb(245, 71, 71);
}
.nextOne {
  margin-top: 25px;

  background-color: #0096fe;
}
::v-deep .el-dialog__footer {
  /*width: 0;宽度为0隐藏*/
  text-align: center;
}
// 滚动条样式
::v-deep .el-table__body-wrapper {
  &::-webkit-scrollbar {
    // 整个滚动条
    width: 0; // 纵向滚动条的宽度
    background: rgba(213, 215, 220, 0.3);
    border: none;
  }
  &::-webkit-scrollbar-track {
    // 滚动条轨道
    border: none;
  }
}
::v-deep .el-dialog__header {
  background-color: #ecf1f9;
  border-radius: 10px;
}
::v-deep .el-dialog {
  border-radius: 10px;
}
::v-deep .el-tooltip__popper {
  max-width: 10%;
}

::v-deep .el-tooltip__popper,
.el-tooltip__popper.is-dark {
  background: rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
::v-deep .el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: auto;
}

::v-deep .el-table th.gutter {
  display: none;
  width: 0;
}
::v-deep .el-table colgroup col[name="gutter"] {
  display: none;
  width: 0;
}

::v-deep .el-table__body {
  width: 100% !important;
}
</style>
  